<template>
    <el-dialog title="新增物资信息" :visible.sync="localVisible" @close="handleClose">
        <el-form ref="form" :model="form" :rules="rules" label-width="120px">
            <el-form-item label="设备类型" prop="type">
                <el-input v-model="form.type"></el-input>
            </el-form-item>
            <el-form-item label="设备型号" prop="model">
                <el-input v-model="form.model"></el-input>
            </el-form-item>
            <el-form-item label="设备厂商" prop="manufacturer">
                <el-input v-model="form.manufacturer"></el-input>
            </el-form-item>
            <el-form-item label="设备使用区域" prop="area">
                <el-select v-model="form.area" placeholder="请选择区域">
                    <el-option v-for="area in areas" :key="area" :label="area" :value="area"></el-option>
                </el-select>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="handleClose">取消</el-button>
            <el-button type="primary" @click="handleSubmit">保存</el-button>
        </div>
    </el-dialog>
</template>

<script>
import axios from 'axios';

export default {
    props: {
        visible: {
            type: Boolean,
            default: false
        },
        isEdit: {
            type: Boolean,
            default: false
        }
    },
    data() {
        return {
            localVisible: this.visible,
            form: {
                type: '',
                model: '',
                manufacturer: '',
                area: ''
            },
            areas: [] ,
            rules: {
                type: [{ required: true, message: '请输入设备类型', trigger: 'blur' }],
                model: [{ required: true, message: '请输入设备型号', trigger: 'blur' }],
                manufacturer: [{ required: true, message: '请输入设备厂商', trigger: 'blur' }],
                area: [{ required: true, message: '请选择设备使用区域', trigger: 'change' }]
            }
        };
    },
    watch: {
        visible(newVal) {
            this.localVisible = newVal;
        },
        localVisible(newVal) {
            this.$emit('update:visible', newVal);
        },

    },
    methods: {
        handleClose() {
            this.localVisible = false;
        },
        handleSubmit() {
            console.log(this.form)
            axios.post('/api/stock/add', this.form).then((response) => {
                console.log(response.data)
                if (response.data.success) {
                    this.$message.success('新增成功');
                    this.handleClose();
                } else {
                    this.$message.error('该物资信息已存在');
                }
            }).catch((error) => {
                this.$message.error('新增失败');
            });
        }
    },
    mounted(){
        axios.post('/api/stock/areas')
        .then(res=>{
            this.areas=res.data;
        })
    }
};
</script>